package com.shuiyu.cloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.shuiyu.cloud.service.PaymentHystrix;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author rjw
 * <p>Description:   </p>
 * @ClassName PaymentHystrixController
 * @time 2021/7/17 13:11
 */

//在生产者和消费者都有fallback的时候，不管生产者自己是不是OK的，消费者这边feign调用异常的时候，都会走消费者自己的fallback

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_Fallback")
public class OrderHystrixController {

    @Resource
    private PaymentHystrix paymentHystrix;


    @GetMapping("/consumer/hystrix/OK/{id}")
    public String payment_OK(@PathVariable("id") Integer id){
        return paymentHystrix.payment_OK(id);
    }

    /**
     * 模拟异常
     * @param id
     * @return
     */
    @GetMapping("/consumer/hystrix/TimeOut/{id}")
    /*@HystrixCommand(fallbackMethod = "consumerPaymentinfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")  //表示这个方法的执行在3秒之内就是正常的，否则会走fallback
    })*/
    @HystrixCommand  //加了@DefaultProperties属性注解，并且没有写具体方法名字，就用统一全局的
    public String paymentinfo_TimeOut(@PathVariable("id") Integer id){
        int a=20/0;
      return paymentHystrix.payment_TimeOut(id);
    }

    /**
     * 这个是兜底的方法（服务降级），上面的出现问题，走这个，模拟消费者调用生产者是出现超时，消费者自己处理服务降级，返回消费者自己声明的fallback
     * @param id
     * @return
     */
    public String consumerPaymentinfo_TimeOutHandler(Integer id){
        //走这里，会用Hystrix里面的线程池
        return "线程池"+Thread.currentThread().getName()+"  对方系统繁忙，请10秒钟之后再试,id:"+id+"\t"+"消费者兜底了------";
    }


    //下面是全局fallback
    public String payment_Global_Fallback(){
        return "Global异常处理信息，请稍后再试，~~~~~~";
    }
}
